package com.bawei.solr;

import java.util.List;
import java.util.Map;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 高亮查询代码演示
 *D:\apache-tomcat-7.0.68_solr\bin
 */
public class HightlightTest {

	private static final Logger LOGGER = LoggerFactory
			.getLogger(LuceneTest.class);

	public static void main(String[] args) {

		String solrUrl = "http://localhost:28080/solr/mycore2";
		HttpSolrClient client = new HttpSolrClient(solrUrl);

		SolrQuery query = new SolrQuery("title:我是");
		// 需要高亮显示的字段
		query.addHighlightField("title");
		
		query.setHighlight(true); // 启用高亮查询
		// 高亮内容+前缀、后缀
		query.setHighlightSimplePre("<font color=\"red\">")
				.setHighlightSimplePost("</font>");

		query.setStart(0);
		query.setRows(10);

		QueryResponse res = null;
		try {
			System.out.println(query);
			res = client.query(query);

			// Map的Key为document的Id，即你在schema.xml中设置的Id，Value为该Id对应的document的值，请听下面分
			// 解，Value也为一个Map，该Map的Key为fieldName，Value为List<String>，这个List里面的内容该文
			// 档的高亮字段。
			Map<String, Map<String, List<String>>> hlMap = res
					.getHighlighting();

			SolrDocumentList sdl = res.getResults();
			for (SolrDocument sd : sdl) {
				String id = (String) sd.get("id");
				// 在solr这里对需要加高亮的字段必须要在索引中的store=true才行
				System.out.println(id + "#"
						+ hlMap.get(id).get("title").get(0));
				System.out.println(sd);
			}
		} catch (SolrServerException e) {
			LOGGER.error(e.getMessage(), e);
		}

	}
}
